package com.lagou.edu.service.impl;

import com.lagou.edu.dao.TokenDao;
import com.lagou.edu.dao.UserDao;
import com.lagou.edu.pojo.Token;
import com.lagou.edu.pojo.User;
import com.lagou.edu.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Example;
import org.springframework.stereotype.Service;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;
import java.util.UUID;

@Service
public class UserServiceImpl implements UserService {
    private static String SESSION_ID = "lagouSessionId";

    @Autowired
    private UserDao userDao;

    @Autowired
    private TokenDao tokenDao;

    @Override
    public boolean isRegistered(String email) {

        User user = new User();
        user.setEmail(email);
        Long count = userDao.count(Example.of(user));
        return count > 0;
    }

    @Override
    public boolean register(HttpServletResponse response, String email, String password) {
        //存储用户信息
        User user = new User();
        user.setEmail(email);
        user.setPassword(password);
        userDao.save(user);
        //存储token信息，因为注册成功后会直接调整到欢迎页，需要生产一下token
        String token = UUID.randomUUID().toString();
        Token lagouToken = new Token();
        lagouToken.setEmail(email);
        lagouToken.setToken(token);
        tokenDao.save(lagouToken);
        Cookie cookie = new Cookie(SESSION_ID,token);
        cookie.setPath("/");
        response.addCookie(cookie);
        return true;
    }

    @Override
    public boolean login(HttpServletResponse response, String email, String password) {
        User user=new User();
        user.setEmail(email);
        user.setPassword(password);
        User lagouUser = userDao.findOne(Example.of(user)).get();
        if(lagouUser == null){
            return false;
        }
        String tokenId = UUID.randomUUID().toString();
        Token token=new Token();
        Token lagouToken = tokenDao.findOne(Example.of(token)).get();
        if(lagouToken == null){
            lagouToken = new Token();
        }
        //更新token
        lagouToken.setToken(tokenId);
        tokenDao.save(lagouToken);
        Cookie cookie = new Cookie(SESSION_ID,tokenId);

        //不设置这个浏览器获取不到cookie
        cookie.setPath("/");
        response.addCookie(cookie);
        return true;
    }
}
